package com.xingkeduo.remote;

import com.alibaba.fastjson.JSON;
import com.xingkeduo.dto.OrderDetailResponseDto;
import com.xingkeduo.dto.RefreshCodeResponseDto;
import com.xingkeduo.dto.transter.CancelPay;
import com.xingkeduo.dto.transter.comment.CommentSubmit;
import com.xingkeduo.dto.transter.commentfinish.CommentFinishParameterDto;
import com.xingkeduo.dto.transter.order.UnpaidOrderRecord;
import com.xingkeduo.dto.transter.shop.ShopsDTO;
import com.xingkeduo.pojo.enums.OrderStatus;
import com.xingkeduo.remote.feign.OrderFeignService;
import com.xingkeduo.util.pojo.exception.BusinessException;
import com.xingkeduo.utils.DateTimeUtils;
import com.xingkeduo.utils.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;


@Service
@Slf4j
public class OrderRemoteService {

    @Resource
    private OrderFeignService orderFeignService;

    @Resource
    private AdminRemoteService adminRemoteService;

    @Resource
    private StoreRemoteService storeRemoteService;

    public String getAdminId(String orderNo){
        ResponseUtils<OrderDetailResponseDto> responseUtils = orderFeignService.queryByOrderNO(orderNo);
        if(responseUtils.success()){
            OrderDetailResponseDto data = responseUtils.getData();
            return String.valueOf(data.getAdminId());
        }
        return null;
    }


    /**
     * 根据订单NO 获取发型师头像
     * @param orderNo
     * @return
     */
    public String getAdminImg(String orderNo){
       return adminRemoteService.getAdminImg(getAdminId(orderNo));
    }


    /**
     * 获取订单验票码二维码
     * @param orderNo
     * @return
     */
    public String getObtainCode(String orderNo){
        ResponseUtils<RefreshCodeResponseDto> responseUtils  = orderFeignService.obtainCode(orderNo);
        if(responseUtils.success()){
            return  responseUtils.getData().getTicketCode();
        }
        return null;
    }

    /**
     * 获取订单详情
     * @return
     */
    public ResponseUtils<OrderDetailResponseDto> queryByOrderNO(String orderNo){
        ResponseUtils<OrderDetailResponseDto> responseDtoResponseUtils = orderFeignService.queryByOrderNO(orderNo);
        if(!responseDtoResponseUtils.success()){
            throw new BusinessException(BusinessException.Type.DEFAULT, "该订单不存在");
        }

        return responseDtoResponseUtils;
    }


    /**
     * 获取店铺id
     * @param responseDtoResponseUtils
     * @return
     */
    public int queryStoreId(ResponseUtils<OrderDetailResponseDto> responseDtoResponseUtils){
        if(!responseDtoResponseUtils.success()){
            throw new BusinessException(BusinessException.Type.DEFAULT, "该订单不存在");
        }
        OrderDetailResponseDto data = responseDtoResponseUtils.getData();
        return Integer.valueOf(data.getStoreId());
    }


    /**
     * 根据orderNo获取订单id
     * @param orderNo
     * @return
     */
    public String queryByOrder(String orderNo){
        ResponseUtils<OrderDetailResponseDto> responseDtoResponseUtils = orderFeignService.queryByOrderNO(orderNo);
        if(!responseDtoResponseUtils.success()){
            throw new BusinessException(BusinessException.Type.DEFAULT, "该订单不存在");
        }
        OrderDetailResponseDto data = responseDtoResponseUtils.getData();
        return data.getId()+"";
    }


    /**
     * 获取订单状态
     * @param commentFinishParameterDto
     * @return
     */
    public boolean orderStatus(CommentFinishParameterDto commentFinishParameterDto) {
//        Todo   调用远程接口 判断该订单问卷是否提交过
        return false;
    }


    /**
     * 判断订单是否超过一个月
     * @return
     */
    public CommentSubmit queryOrder(String orderNo){
        ResponseUtils<OrderDetailResponseDto> responseDtoResponseUtils = orderFeignService.queryByOrderNO(orderNo);
        if(responseDtoResponseUtils.success() && responseDtoResponseUtils.getData()!=null){
            boolean bf = DateTimeUtils.judgementTime(responseDtoResponseUtils.getData().getCreatedTime());
            if(!bf){
                CommentSubmit commentSubmit = new CommentSubmit();
                commentSubmit.setError(7);
                commentSubmit.setReason("很抱歉，下单时间超过14天的订单无法评价！");
                return commentSubmit;
            }
        }
        return null;
    }


    public UnpaidOrderRecord getUnpaidOrderRecord(String userId){
        ResponseUtils<OrderDetailResponseDto> notPayOrderInfo = orderFeignService.getNotPayOrderInfo(userId);
        if(notPayOrderInfo.success() && notPayOrderInfo.getData()!=null){
            OrderDetailResponseDto o = notPayOrderInfo.getData();
            UnpaidOrderRecord u = new UnpaidOrderRecord();
            ShopsDTO shopsDTO = storeRemoteService.queryStoreById(Integer.valueOf(o.getStoreId()));
            String storeName=  shopsDTO==null?o.getStoreName():shopsDTO.getName();
            String address=  shopsDTO==null?"":shopsDTO.getAddress();
            ArrayList<String> list = new ArrayList<>();
            String pay = String.valueOf(o.getPayPrice());
            int num = pay.indexOf(".");
            list.add( pay.indexOf(".")>0?pay.substring(0,num):pay);
            list.add( pay.indexOf(".")>0?pay.substring(num+1,pay.length()):"00");
            o.getStoreId();
            u.setIs_product(false);
            u.setProduct_id("");
            u.setStore_name(storeName);
            u.setStatus("1");
            u.setStatus_name(o.getStatusName());
            u.setType(o.getPayTypeName());
            u.setProduct_name("");
            u.setProduct_nums("1");
            u.setMode("2");
            u.setServer_name(o.getServiceTypeName());
            u.setPay_time("");
            u.setAppointment_time(DateTimeUtils.HH_mm(o.getAppointmentStartTime()));
            u.setAddress(address);
            u.setOrder_no(o.getOrderNo());
            u.setOut_order_no(o.getOutOrderNo());
            u.setCoupon_price(String.valueOf(o.getCouponPrice()));
            u.setPay_price(list);
            u.setDiscount_price(String.valueOf(o.getAllPrice().subtract(o.getPayPrice())));
            u.setMarket_sell_price(o.getAllPrice().toString());
            u.setImg_url(adminRemoteService.getAdminImg(o.getAdminId()));
            u.setCan_buy(false);
            u.setCan_refund(false);
            u.setStore_id(o.getStoreId());
            u.setAdmin_name(adminRemoteService.getAdminName(o.getAdminId()));
            return u;
        }
        return null;

    }



    public CancelPay cancelOrder(String userId, String orderNo) {
        CancelPay cancelPay = new CancelPay();
        ResponseUtils<OrderDetailResponseDto> responseDtoResponseUtils = orderFeignService.queryByOrderNO(orderNo);
        OrderDetailResponseDto data = responseDtoResponseUtils.getData();
        if(OrderStatus.CLOSE.equals(data.getStatus()) || OrderStatus.CANCEL.equals(data.getStatus())){
            cancelPay.setError(0);
            cancelPay.setReason(0);
            cancelPay.setContent(true);
            return cancelPay;
        }
        ResponseUtils cancelOrder = orderFeignService.cancelOrder(userId,orderNo);
        cancelPay.covert(cancelOrder);
        return cancelPay;
    }


    /**
     * 获取未支付订单
     * @param userId
     * @return
     */
    public Boolean getNotPayOrderNo(String userId){
        ResponseUtils<String>  responseUtils =orderFeignService.getNotPayOrderNo(userId);
        if(responseUtils.success()){
            String data = responseUtils.getData();
            if(StringUtils.isNotBlank(data)){
                return false;
            }

        }
        return false;
    }


    //获取用户类型
    public Integer queryUserType(String userId,String storeId){
        log.info("获取用户类型 userId:{}", userId);
        log.info("获取用户类型 storeId:{}", storeId);
        ResponseUtils<Integer> integerResponseUtils = orderFeignService.queryUserType(userId, storeId);
        log.info("获取用户类型 integerResponseUtils:{}", JSON.toJSONString(integerResponseUtils));
        return integerResponseUtils.getData();
    }


}
